<?php

declare(strict_types=1);

namespace app\common\Image;

use app\common\Image\BaseImage;

class Base64Handle extends BaseImage
{

    // base64转图片
    public function base64ToImage($base64Image)
    {
        $return = [
            'url' => '',
            'result' => false,
            'message' => ''
        ];
        if (empty($base64Image)) {
            $return['message'] = '没有接收到图片数据';
            return $return;
        }

        try {
            // 解析 Base64 编码的图片数据
            if (preg_match('/^data:image\/(\w+);base64,/', $base64Image, $type)) {
                $data = substr($base64Image, strpos($base64Image, ',') + 1);
                $type = strtolower($type[1]); // jpg, png, gif 等
                if (!in_array($type, $this->image['limit']['type_limit'])) {
                    $return['message'] = '不支持的图片格式';
                    return $return;
                }
                $data = base64_decode($data);
                if ($data === false) {
                    $return['message'] = 'Base64 解码失败';
                    return $return;
                }
            } else {
                $return['message'] = '不正确的 Base64 图片数据';
                return $return;
            }

            // 保存图片到文件
            if (empty($url)) $url = $this->image['temp_path'];
            if (!is_dir($url)) {
                mkdir($url, 0755, true);
            }
            if (empty($name)) $name = $this->createFileName($type);

            $tempFile = $url . $name;

            file_put_contents($tempFile, $data);
            $return['url'] = $tempFile;
            $return['result'] = true;
            $return['message'] = 'Successful operation';
            return $return;
        } catch (\Exception $e) {
            $return['message'] = $e->getMessage();
            return $return;
        }
    }
}
